<?php


namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Response\JsonResult;
use App\Http\Response\ResponseCode;
use App\Http\Validates\Admin\System\AdminValidates;
use App\Models\System\SystemAdminModel;
use App\Service\Command\Admin\System\AdminCommandService;
use App\Service\Query\Admin\System\AdminQueryService;
use App\Service\Query\Admin\System\RoleQueryService;
use Illuminate\Http\Request;

class ManagerController extends BaseController
{
    protected $queryService   = AdminQueryService::class;
    protected $commandService = AdminCommandService::class;
    protected $model = SystemAdminModel::class;
    protected $validate = AdminValidates::class;
    protected $viewAuthRoute = ['add'=>'/system/admin/add','update'=>'/system/admin/update','password'=>'/system/admin/password'];


    //展示个人信息
    public function index()
    {
        return  $this->lists_index();
    }

    public function add(Request $request)
    {
        if ( $request->ajax() ) {
            return parent::add($request);
        }

        $roles = app(RoleQueryService::class)->getAll(['id','name']);
        $rolesJson = [];
        foreach ($roles as $role) {
            if ( $role->id > 1 ) {
                $rolesJson[] = ['name'=>$role->name,'value'=>$role->id];
            }
        }
        return view('admin.system.manager.form',['roles'=>$roles,'rolesJson'=>$rolesJson]);
    }

    public function update(Request $request)
    {
        if ( $request->ajax() ) {
            return parent::update($request);
        }

        $roles = app(RoleQueryService::class)->getAll(['id','name']);
        $this->model = app($this->model);
        $info = $this->model->find($request->input('id'));
        $infoRoles = $info->roles()->get(['role_id'])->toArray();

        $roleIds = array_column($infoRoles,'role_id');

        $rolesJson = [];
        foreach ($roles as $role) {
            if ( $role->id > 1 ) {

                if ( in_array($role->id,$roleIds) ) {
                    $rolesJson[] = ['name'=>$role->name,'value'=>$role->id,'selected' =>true];
                } else {
                    $rolesJson[] = ['name'=>$role->name,'value'=>$role->id];
                }

            }
        }

        return view('admin.system.manager.form',['roles'=>$roles,'info'=>$info,'rolesJson'=>$rolesJson]);
    }


    public function password(Request $request)
    {
        if ( $request->ajax() ) {
            $request->validate( app($this->validate)->password );
            $info = app($this->model)->find($request->input('id'));
            if (empty($info)) {
                return JsonResult::returnJson(ResponseCode::DATA_NOT_EXIST);
            }

            $info->password = bcrypt($request->input('password'));
            $info->save();
            return JsonResult::returnJson(ResponseCode::SUCCESS);
        }

        return view('admin.system.manager.password');
    }

}